import React, { ChangeEvent, FC, useEffect, useRef, useState } from "react";
import "./RuleManage.css";
import {
  Button,
  Cascader,
  DatePicker,
  Descriptions,
  Drawer,
  Form,
  Input,
  message,
  Modal,
  Select,
  Table,
  Tabs,
  Tag,
  TimePicker,
} from "antd";
import { useRequest } from "@umijs/hooks";
import { fetchRequest } from "@/utils/Request";
import { url } from "@/utils/url";
import { getOriginString, getSecretString } from "@/utils/encrypt";
import {
  ApiOutlined,
  CloseOutlined,
  DeleteOutlined,
  EditOutlined,
  ExclamationCircleOutlined,
  EyeOutlined,
  FallOutlined,
  PlusOutlined,
  ReloadOutlined,
  SearchOutlined,
} from "@ant-design/icons";

// @ts-ignore
import shortid from "shortid";
import moment, { Moment } from "moment/moment";
import XLSX from "xlsx";
import RuleStudent from "@/containers/RuleManage/view/RuleStudent";

const { TabPane } = Tabs;
const { Option } = Select;
const { RangePicker } = TimePicker;
const { RangePicker: DateRangePicker } = DatePicker;
const { confirm } = Modal;
const timerList = [
  {
    title: "星期一",
    value: 1,
  },
  {
    title: "星期二",
    value: 2,
  },
  {
    title: "星期三",
    value: 3,
  },
  {
    title: "星期四",
    value: 4,
  },
  {
    title: "星期五",
    value: 5,
  },
  {
    title: "星期六",
    value: 6,
  },
  {
    title: "星期天",
    value: 7,
  },
];

const layout = {
  labelCol: { span: 4 },
  wrapperCol: { span: 20 },
};

interface requestParamTree {
  level: number;
  treeId?: string;
}

const params = {
  ruleId: "",
  ruleName: "",
  ruleType: "1",
  weekDay: [],
  normalTimes: [],
  specialEndDate: "",
  specialStartDate: "",
  deptId: "",
};

let importFlag = true;

let changeItem = false; //是否修改

const RuleManage: FC = () => {
  return (
    <>
      <div className={"rule-tabs"}>
        <Tabs>
          <TabPane tab="规则管理" key="1">
            <Rule />
          </TabPane>
          <TabPane tab="学生一般规则管理" key="2">
            <RuleStudent />
          </TabPane>
        </Tabs>
      </div>
    </>
  );
};

const Rule: FC = () => {
  const errorcolumns = [
    {
      title: "学生姓名",
      dataIndex: "studentName",
      key: "studentName",
    },
    {
      title: "白卡号",
      dataIndex: "whiteCode",
      key: "whiteCode",
    },
    {
      title: "电话号码",
      dataIndex: "phone",
      key: "phone",
      render: (text: string) => {
        console.log(text);
        return <>{getOriginString(text)}</>;
      },
    },
    {
      title: "错误说明",
      dataIndex: "errorDescription",
      key: "errorDescription",
    },
  ];
  const columns = [
    {
      title: "规则名称",
      key: "ruleName",
      dataIndex: "ruleName",
    },
    {
      title: "规则类型",
      key: "ruleType",
      dataIndex: "ruleType",
      render: (ruleType: number) => {
        return <>{ruleType == 1 ? "一般规则" : "特殊规则"}</>;
      },
    },
    {
      title: "创建时间",
      key: "createdAt",
      dataIndex: "createdAt",
    },
    {
      title: "操作",
      render: (item: any) => {
        const btn =
          item.ruleType === 1 ? (
            <>
              <Tag
                color={"#87d068"}
                icon={<FallOutlined />}
                className={"pointer enable"}
                onClick={() => onImport(item)}
              >
                导入
              </Tag>
            </>
          ) : null;
        return (
          <>
            <Tag
              color={"#108ee9"}
              icon={<EyeOutlined />}
              className={"pointer"}
              onClick={() => selectRuleInfo(item)}
            >
              查看
            </Tag>
            <Tag
              color={"#108ee9"}
              icon={<EditOutlined />}
              className={"pointer"}
              onClick={() => onEdit(item)}
            >
              修改
            </Tag>
            {btn}
            <Tag
              color={"rgb(255, 85, 0)"}
              icon={<DeleteOutlined />}
              className={"pointer delete"}
              onClick={() => onDelete(item)}
            >
              删除
            </Tag>
          </>
        );
      },
    },
  ];
  const importColumns = [
    {
      title: "电话号码",
      key: "phone",
      dataIndex: "phone",
      render: (text: string) => {
        if (text === "") {
          importFlag = false;
          return <Tag color={"#f50206"}>电话号码未填</Tag>;
        }
        if (!/^1[3-9]\d{9}$/.test(text)) {
          importFlag = false;
          return <Tag color={"#f50206"}>电话号码格式错误</Tag>;
        }
        return text;
      },
    },
    {
      title: "学生姓名",
      key: "studentName",
      dataIndex: "studentName",
      render: (text: string) => {
        if (text === "") {
          importFlag = false;
          return <Tag color={"#f50206"}>学生姓名未填</Tag>;
        }

        if (!(/^[\u4e00-\u9fa5]{0,}$/.test(text) || /^[A-Za-z]+$/.test(text))) {
          importFlag = false;
          return <Tag color={"#f50206"}>学生姓名格式错误</Tag>;
        }
        return text;
      },
    },
    {
      title: "白卡卡号",
      key: "whiteCode",
      dataIndex: "whiteCode",
      render: (text: string) => {
        if (text === "") {
          importFlag = false;
          return <Tag color={"#f50206"}>白卡卡号未填</Tag>;
        }

        if (!/^[0-9]*$/.test(text)) {
          importFlag = false;
          return <Tag color={"#f50206"}>白卡卡号格式错误</Tag>;
        }
        return text;
      },
    },
  ]; //导入的TABLE的col
  const input = useRef<HTMLInputElement>(null);
  const [ruleType, setRuleType] = useState("");
  const [ruleName, setRuleName] = useState("");
  const [isModalVisible, setIsModalVisible] = useState(false); //导入弹窗
  const [importTable, setImportTable] = useState<any[]>([]); // 导入的导入的TABLE
  const [errorTable, setErrorTable] = useState([]); //错误信息TAble
  const [data, setData] = useState<any>(null);

  //弹出cen
  const [visible, setVisible] = useState(false);

  const [treeNode, setTreeNode] = useState<any>([]);

  const [requestParamTree, setRequestParamTree] = useState<requestParamTree>({
    level: 0,
    treeId: "0",
  });
  //table的key
  const [tableKey, setTableKey] = useState("1");
  const [isAdd, setIsAdd] = useState(true);
  const [itemId, setItemId] = useState("");

  const [initialValues, setInitialValues] = useState<any>({
    deptId: "",
  });

  const [form] = Form.useForm();
  const [dForm] = Form.useForm();

  //添加和修改
  const { loading, run: addAndEditRun } = useRequest(
    () => fetchRequest(url.RULE_ADD_UPDATE, params),
    {
      manual: true,
      onSuccess: async (result, params) => {
        if (result.success) {
          setVisible(false);
          await refresh();
          message.success(result.data);
        } else {
          message.error(result.errorMsg);
        }
      },
    }
  );
  //删除
  const { run: deleteRun } = useRequest(
    (params) => fetchRequest(url.RULE_DELETE, params),
    {
      manual: true,
      onSuccess: async (result, params: any) => {
        if (result.success) {
          await refresh();
          message.success(result.data);
        } else {
          message.error(result.errorMsg);
        }
      },
    }
  );

  //导入人员
  const { loading: importLoading, run: importRun } = useRequest(
    (params) => fetchRequest(url.RULE_IMPORT, params),
    {
      manual: true,
      onSuccess: async (result, params: any) => {
        if (result.success) {
          const data = result.data;
          setErrorTable(data.errorDescriptionVos);
          setData(data);
          message.info(`成功${data.countSuccess},失败${data.countFail}`);
        } else {
          message.error(result.errorMsg);
        }
      },
    }
  );

  const { tableProps, run, refresh } = useRequest(
    (current, params) =>
      fetchRequest(url.RULE_TABLE, {
        pageSize: current.pageSize,
        pageStart: current.current,
        ...params,
      }),
    {
      paginated: true,
      manual: true,
      formatResult: (response: any) => {
        return {
          list: response.data?.rows,
          total: response.data?.total,
          success: response.success,
          errorMsg: response.errorMsg,
        };
      },
    }
  );

  //点击修改
  const onEdit = (item: any) => {
    changeItem = false;
    setVisible(true);
    setIsAdd(false);
    setTableKey(`${item.ruleType}`);
    params.ruleId = item.id;

    if (item.ruleType === 1) {
      form.setFieldsValue({
        ...item,
        accessBox: {
          state: item?.normalTimes?.map((item: string) => {
            const tempList = item
              .split("-")
              .map((item) => moment(item, "HH:mm:ss"));
            return { id: shortid.generate(), value: tempList };
          }),
        },
      });
    }
    if (item.ruleType === 2) {
      dForm.setFieldsValue({
        ...item,
        deptId: [item.deptName],
        time: [moment(item.specialStartDate), moment(item.specialEndDate)],
      });
    }
  };

  //点击确定
  const onFinish = async (values: any) => {
    params.ruleName = values.ruleName;
    params.ruleType = `${tableKey}`;
    if (tableKey == "1") {
      params.weekDay = values.weekDay;
      params.normalTimes = values.accessBox.state.map((item: any) => {
        if (item.value) {
          const tempList = item.value.map((timer: Moment) =>
            timer.format("HH:mm")
          );
          return `${tempList[0]}-${tempList[1]}`;
        }
      });
    } else {
      params.deptId = changeItem
        ? values.deptId[values.deptId.length - 1]
        : tableProps.dataSource.find((item: any) => item.id === params.ruleId)
            .deptId;
      params.specialStartDate = values.time[0].format("YYYY-MM-DD HH:mm:ss");
      params.specialEndDate = values.time[1].format("YYYY-MM-DD HH:mm:ss");
    }

    await addAndEditRun();
  };
  //点击删除
  const onDelete = async (item: any) => {
    confirm({
      title: "删除",
      icon: <ExclamationCircleOutlined />,
      content: "确认删除该规则吗?",
      okText: "确定",
      okType: "danger",
      cancelText: "取消",
      async onOk() {
        await deleteRun({ id: item.id });
      },
      onCancel() {},
    });
  };

  const onImport = async (item: any) => {
    // input.current!.click()
    setIsModalVisible(true);
    setErrorTable([]);
    setImportTable([]);
    setItemId(item.id);
  };

  const fileChange = async (e: ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    importFlag = true;
    setErrorTable([]);
    if (file) {
      const list = await handleExcelFile<any[]>(file);
      const tempList = list.map((item) => ({
        phone: `${item["电话号码"]}`,
        studentName: item["学生姓名"],
        whiteCode: item["白卡卡号"],
        rowNum: item.__rowNum__,
      }));
      setImportTable(tempList);
    }
  };

  const handleExcelFile = <T,>(file: File) => {
    let reader = new FileReader(); // 使用 FileReader 读取数据

    return new Promise<T>((resolve, reject) => {
      reader.onload = function (e) {
        // 数据读取完成后的回调函数
        try {
          let workbook = XLSX.read(e.target?.result, { type: "binary" });
          let firstSheetName = workbook.SheetNames[0]; // 获取第一个 sheet 的名字
          let worksheet = workbook.Sheets[firstSheetName]; // 获取第一个 sheet 的内容
          let res = XLSX.utils.sheet_to_json(worksheet) as unknown as T; // 使用 utils 里的方法转换内容为便于使用的数组
          resolve(res);
        } catch (e) {
          message.error("数据异常！");
          reject(e);
        }
      };
      reader.readAsBinaryString(file); // 读取数据
    });
  };

  //请求在校学生组织机构
  async function getSchoolOrganizationRequest(params: requestParamTree) {
    try {
      const json = await fetchRequest(url.GET_SCHOOL_ORGANIZATION, params);
      if (json.success) {
        message.destroy();
        json.data.forEach((item: any) => {
          delete item.children;
        });
        setTreeNode(json.data);
      } else {
        message.destroy();
        message.error(json.errorMsg);
      }
    } catch (error: any) {
      message.destroy();
      message.error(error.message);
    }
  }

  const onChange = (value: any, selectedOptions: any) => {
    changeItem = true;
  };

  const loadData = async (selectedOptions: any) => {
    const targetOption = selectedOptions[selectedOptions.length - 1];
    targetOption.loading = true;

    //组装参数
    const params: requestParamTree = {
      level: 0,
      treeId: "0",
    };
    selectedOptions.map((item: any) => {
      params.treeId = item.treeId;
      params.level = selectedOptions.length;
    });
    // console.log(params)

    fetchRequest(url.GET_SCHOOL_ORGANIZATION, params)
      .then((json) => {
        if (json.success) {
          console.log(json.data);
          json.data.map((item: any) => {
            delete item.children;
          });
          targetOption.children = json.data;
          // console.log(targetOption)
        } else {
          message.error(json.errMsg);
        }
      })
      .catch((error) => {
        console.log(error);
      })
      .finally(() => {
        targetOption.loading = false;
        //主动刷新页面
        setTreeNode([...treeNode]);
      });
  };

  const onSearch = async () => {
    await run({ pageSize: 10, current: 1 }, { ruleName: ruleName, ruleType });
  };

  //添加规则
  const addRule = () => {
    setVisible(true);
    setIsAdd(true);
    setTableKey("1");
    params.ruleId = "";

    form.resetFields();
    dForm.resetFields();
  };
  const importClick = async () => {
    if (!importFlag) {
      message.error("excel有错误");
      return;
    }

    if (!importTable.length) {
      message.error("请选择文件");
      return;
    }

    await importRun({
      batchRuleAndStudentDtoList: importTable.map((item) => ({
        ...item,
        phone: getSecretString(item.phone),
      })),
      ruleId: itemId,
    });
  };

  const changeRule = (value: string) => {
    setRuleType(value);
  };

  const reset = async () => {
    setRuleName("");
    setRuleType("");
    await run({ pageSize: 10, current: 1 }, { ruleName: "", ruleType: "" });
  };

  useEffect(() => {
    getSchoolOrganizationRequest(requestParamTree);
  }, [requestParamTree]);

  useEffect(() => {
    onSearch();
  }, []);

  const [ruleInfoShow, setRuleInfoShow] = useState(false);
  const [ruleInfo, setRuleInfo] = useState<any>({});
  //查询规则信息
  const selectRuleInfo = (item: any) => {
    setRuleInfo(item);
    setRuleInfoShow(true);
  };

  const boRender = () => (
    <>
      <div className={"search-wrap"}>
        <div className={"search-title"}>规则名称：</div>
        <div className={"search-value"}>
          <Input
            value={ruleName}
            onChange={(e) => setRuleName(e.target.value)}
          />
        </div>
        <div className={"search-title"}>规则类型:</div>
        <div className={"search-value"}>
          <Select
            defaultValue={""}
            value={ruleType}
            style={{ width: 100 }}
            onChange={changeRule}
          >
            <Option value={""}>全部</Option>
            <Option value={"1"}>一般规则</Option>
            <Option value={"2"}>特殊规则</Option>
          </Select>
        </div>
        <div className={"search-btn-wrap"}>
          <div>
            <Button
              icon={<SearchOutlined />}
              type={"primary"}
              onClick={onSearch}
            >
              搜索
            </Button>
            <Button icon={<ReloadOutlined />} onClick={reset}>
              重置
            </Button>
          </div>
          <div>
            <Button onClick={addRule} icon={<PlusOutlined />} type={"primary"}>
              添加
            </Button>
          </div>
        </div>
      </div>
    </>
  );

  const drawer = () => (
    <>
      <Drawer
        title={isAdd ? "添加规则" : "修改规则"}
        placement="right"
        closable={false}
        onClose={() => setVisible(false)}
        visible={visible}
        width={800}
      >
        <Tabs
          centered
          activeKey={tableKey}
          onChange={(activeKey: string) => {
            params.ruleType = activeKey;
            setTableKey(activeKey);
          }}
        >
          <TabPane tab="一般规则" key={1} disabled={tableKey !== "1" && !isAdd}>
            <Form
              onFinish={onFinish}
              form={form}
              {...layout}
              initialValues={{
                accessBox: {
                  state: [
                    { id: shortid.generate(), value: "" },
                    { id: shortid.generate(), value: "" },
                  ],
                },
              }}
            >
              <Form.Item
                label="规则名称"
                name="ruleName"
                rules={[{ required: true }]}
                wrapperCol={{ span: 11 }}
              >
                <Input placeholder="请输入规则名称" />
              </Form.Item>
              <Form.Item
                label="星期"
                name="weekDay"
                rules={[{ required: true }]}
              >
                <Select mode="multiple" allowClear placeholder="请选择星期">
                  {timerList.map((item) => (
                    <Option key={item.title} value={item.value}>
                      {item.title}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
              <Form.Item
                label="规则时间"
                name="accessBox"
                rules={[{ required: true }]}
              >
                <AccessBox />
              </Form.Item>
              <Form.Item className={"btn-wrap"} wrapperCol={{ span: 24 }}>
                <Button type="primary" htmlType="submit" loading={loading}>
                  确定
                </Button>
                <Button
                  type="primary"
                  htmlType="button"
                  onClick={() => form.resetFields()}
                >
                  重置
                </Button>
              </Form.Item>
            </Form>
          </TabPane>
          <TabPane tab="特殊规则" key={2} disabled={tableKey !== "2" && !isAdd}>
            <Form
              onFinish={onFinish}
              form={dForm}
              {...layout}
              initialValues={initialValues}
            >
              <Form.Item
                label="规则名称"
                name="ruleName"
                rules={[{ required: true }]}
                wrapperCol={{ span: 11 }}
              >
                <Input placeholder="请输入规则名称" />
              </Form.Item>

              <Form.Item
                className="form-control-item"
                name="deptId"
                label="组织机构"
                rules={[{ required: true }]}
              >
                <Cascader
                  placeholder="请选择组织机构"
                  options={treeNode}
                  loadData={loadData}
                  changeOnSelect
                  onChange={onChange}
                />
              </Form.Item>
              <Form.Item label="时间" name="time" rules={[{ required: true }]}>
                <DateRangePicker
                  showTime={{ format: "HH:mm" }}
                  format="YYYY-MM-DD HH:mm"
                />
              </Form.Item>
              <Form.Item className={"btn-wrap"} wrapperCol={{ span: 24 }}>
                <Button type="primary" htmlType="submit" loading={loading}>
                  确定
                </Button>
                <Button
                  type="primary"
                  htmlType="button"
                  onClick={() => dForm.resetFields()}
                >
                  重置
                </Button>
              </Form.Item>
            </Form>
          </TabPane>
        </Tabs>
      </Drawer>
    </>
  );

  return (
    <div className={"rule-wrap"}>
      {boRender()}
      {drawer()}
      <Drawer
        placement="right"
        destroyOnClose
        closable={false}
        title="导入"
        visible={isModalVisible}
        onClose={() => {
          setIsModalVisible(false);
          input.current!.value = "";
        }}
        width={800}
      >
        <div className={"import-item"}>
          导入模板:{" "}
          <span className={"import-val"}>
            <a href={require("@/excel/规则人员导入.xlsx")} download>
              模板下载
            </a>
          </span>
        </div>
        <div className={"import-item"}>
          上传文件:{" "}
          <span className={"import-val"}>
            <input
              type="file"
              accept=".xlsx, .xls"
              onChange={(e) => fileChange(e)}
              ref={input}
            />
          </span>
        </div>
        <div className={"import-item"}>数据预览：</div>
        <div className={"import-item"}>
          <Table
            columns={importColumns}
            rowKey={(record) => record.rowNum}
            dataSource={importTable}
            pagination={{
              hideOnSinglePage: true,
              simple: true,
              pageSize: 10,
              total: importTable.length,
            }}
          />
        </div>
        <div className={"import-item"}>
          <Button
            type={"primary"}
            loading={importLoading}
            onClick={importClick}
          >
            提交
          </Button>
        </div>

        <div className={"import-item"}>
          错误提示：
          {data ? (
            <>
              <span className={"success"}>成功:{data.countSuccess}</span>
              <span className={"error"}>失败:{data.countFail}</span>
            </>
          ) : null}
        </div>
        <div className={"import-item"}>
          <Table
            columns={errorcolumns}
            rowKey={(record: any) => record.id}
            dataSource={errorTable}
            pagination={{
              hideOnSinglePage: true,
              simple: true,
              pageSize: 10,
              total: errorTable.length,
            }}
          />
        </div>
      </Drawer>

      <RuleInfo
        setIsVisible={setRuleInfoShow}
        Visible={ruleInfoShow}
        item={ruleInfo}
      />
      <Table columns={columns} rowKey="id" {...(tableProps as any)} />
    </div>
  );
};

const AccessBox: FC<{ value?: any; onChange?: (state: any) => void }> = ({
  value,
  onChange,
}) => {
  //一般规则门禁盒子

  console.log(value?.state);

  const [showBtn, setShowBtn] = useState(true);

  const triggerChange = (changedValue: { state: any[] }) => {
    onChange?.({ ...value, ...changedValue });
  };

  //点击添加门禁盒子
  const addAccess = () => {
    triggerChange({
      state: [...value.state, { value: "", id: shortid.generate() }],
    });
  };

  //删除门禁盒子
  const deleteAccess = (item: any) => {
    if (value.state.length <= 2) {
      message.error("必须保留两个");
      return;
    }
    triggerChange({
      state: value.state.filter((access: any) => access.id !== item.id),
    });
  };

  //选择门禁盒子
  const changeAccess = (timer: any, timeString: any, item: any) => {
    triggerChange({
      state: value.state.map((access: any) => {
        if (access.id === item.id) {
          access.value = timer;
        }
        return access;
      }),
    });
  };

  useEffect(() => {
    setShowBtn(value?.state?.length !== 3);
  }, [value?.state]);

  return (
    <>
      {value?.state?.map((item: any, i: number) => (
        <div key={item.id} className={"access-box-item"}>
          <RangePicker
            allowClear
            value={item.value}
            defaultValue={item.value}
            format="HH:mm"
            onChange={(timer, timeString) =>
              changeAccess(timer, timeString, item)
            }
          />
          {i === 2 ? (
            <Button
              type={"primary"}
              icon={<CloseOutlined />}
              danger
              onClick={() => deleteAccess(item)}
            >
              删除
            </Button>
          ) : null}
        </div>
      ))}
      {showBtn ? (
        <Button type={"primary"} icon={<PlusOutlined />} onClick={addAccess}>
          添加
        </Button>
      ) : null}
    </>
  );
};

const RuleInfo: FC<{
  Visible: boolean;
  setIsVisible: (Visible: boolean) => void;
  item: any;
}> = ({ Visible, setIsVisible, item }) => {
  const columns = [
    {
      title: "学生姓名",
      key: "studentName",
      dataIndex: "studentName",
    },

    {
      title: "电话号码",
      key: "phone",
      dataIndex: "phone",
      render: (text: string) => <>{getOriginString(text)}</>,
    },
    {
      title: "规则状态",
      key: "stateName",
      dataIndex: "stateName",
      render: (text: string, record: any) => {
        const colorList = [
          "#b7eb8f",
          "#69c0ff",
          "#ff7875",
          "#5cdbd3",
          "#69c0ff",
          "#5cdbd3",
          "#ff7875",
          "#69c0ff",
          "#ff7875",
          "#ff7875",
          "#ff7875",
          "#ff7875",
          "#ff7875",
        ];

        return (
          <Tag color={colorList[Number(record.state) - 1]}>
            {record.stateName}
          </Tag>
        );
      },
    },
    {
      title: "备注",
      key: "remark",
      dataIndex: "remark",
    },
    {
      title: "操作",
      render: (item: any) => (
        <>
          <Tag
            color={"rgb(16, 142, 233)"}
            icon={<ApiOutlined />}
            onClick={() => {
              setInfoTable(item.deviceBindingConditionVos);
              setInfoVisible(true);
            }}
          >
            查看设备
          </Tag>
        </>
      ),
    },
  ];
  const infoColumns = [
    {
      title: "设备名称",
      key: "deviceName",
      dataIndex: "deviceName",
    },
    {
      title: "推送状态",
      key: "stateName",
      dataIndex: "stateName",
    },

    {
      title: "备注",
      key: "remark",
      dataIndex: "remark",
    },
  ];

  const [infoVisible, setInfoVisible] = useState(false);
  const [infoTable, setInfoTable] = useState([]);

  const { tableProps, run, refresh } = useRequest(
    (current, params) =>
      fetchRequest(url.RULE_INFO_STUDENT, {
        pageSize: current.pageSize,
        pageStart: current.current,
        ...params,
      }),
    {
      paginated: true,
      manual: true,
      formatResult: (response: any) => {
        return {
          list: response.data?.rows,
          total: response.data?.total,
          success: response.success,
          errorMsg: response.errorMsg,
        };
      },
    }
  );

  useEffect(() => {
    if (item.id && Visible) {
      console.log(1);
      run({ pageSize: 10, current: 1 }, { id: item.id });
    }
  }, [item.id, Visible]);

  return (
    <>
      <Drawer
        placement="right"
        closable={false}
        title="规则详情"
        visible={Visible}
        onClose={() => setIsVisible(false)}
        width={1200}
      >
        <Descriptions bordered>
          <Descriptions.Item label={"规则名称"}>
            {item.ruleName}
          </Descriptions.Item>
          <Descriptions.Item label={"组织机构"}>
            {item.deptName}
          </Descriptions.Item>
          <Descriptions.Item label={"规则类型"}>
            {item.ruleType === 1 ? "一般规则" : "特殊规则"}
          </Descriptions.Item>
          {item.specialStartDate ? (
            <Descriptions.Item
              label={"规则时间"}
            >{`${item.specialStartDate}~${item.specialEndDate}`}</Descriptions.Item>
          ) : null}

          {item.weekDay ? (
            <Descriptions.Item label={"规则星期"}>
              {item.weekDay.map((key: any) => (
                <Tag key={key}>
                  {timerList.find((timer: any) => timer.value === key)?.title}
                </Tag>
              ))}
            </Descriptions.Item>
          ) : null}

          {item.normalTimes ? (
            <Descriptions.Item label={"规则时间"}>
              {item.normalTimes.map((normal: any) => (
                <div key={normal}>{normal}</div>
              ))}
            </Descriptions.Item>
          ) : null}
        </Descriptions>
        <div className={"user-title"}>人员列表</div>
        <Table columns={columns} rowKey={"id"} {...(tableProps as any)} />
      </Drawer>

      <Drawer
        placement="right"
        closable={false}
        title="设备详情"
        visible={infoVisible}
        onClose={() => setInfoVisible(false)}
        width={1000}
      >
        <Table columns={infoColumns} rowKey={"id"} dataSource={infoTable} />
      </Drawer>
    </>
  );
};

export default RuleManage;
